import React from 'react';
import ReactDOM from 'react-dom';
import BlockButtonComponent from './BlockButtonComponent';
import BlockMaskComponent from './BlockMaskComponent';
import { createUser, existBlockUser } from './utils';

console.log("cqmgogo block extension loaded");

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
  if (msg.color) {
    console.log("Receive color = " + msg.color);
    document.body.style.backgroundColor = msg.color;
    sendResponse("Change color to " + msg.color);
  } else {
    sendResponse("Color message is none.");
  }
});


if (isPostDetailPage()) {
  console.log("当前在帖子页面√");
  insertBlockMask();
  insertBlockButton();
}
else {
  console.log("当前不在帖子页面✕");
}

/**
 * 判断当前是否在帖子内容页面
 */

function isPostDetailPage() {
  let currentUrl = window.location.href;
  return currentUrl.includes("thread") && currentUrl.endsWith("1.html")
}

/**
 * 为每一个用户注入BlockButton
 */
function insertBlockButton() {
  // 找到父容器
  let userProfileList = Array.from(document.querySelectorAll("[itemtype='http://rdfs.org/sioc/ns#UserAccount']") as NodeListOf<HTMLElement>);

  if (userProfileList) {
    userProfileList.forEach(async element => {
      // 生成一个容器,作为react的渲染容器
      const container = document.createElement('div');
      // 根据UserProfileElement创建user
      let user = createUser(element);
      let isBlocked = await existBlockUser(user.id);
      // 渲染按钮到指定容器
      ReactDOM.render(
        <React.StrictMode>
          <BlockButtonComponent user={user} isBlocked={isBlocked} />
        </React.StrictMode>,
        container);
      // 将这个容器注入到父容器内
      element.appendChild(container);
    });
  }
  else {
    console.log("找不到block button 注入点");
  }
}

/**
 * 为每一个回帖注入BlockMask
 */
function insertBlockMask() {
  // 找到父容器
  let replayList = Array.from(document.querySelectorAll("[itemtype='http://schema.org/Post']") as NodeListOf<HTMLElement>);
  if (replayList) {
    // 根据UserProfile创建Mask
    replayList.forEach(async element => {
      let userProfileElement = element.querySelector("[itemtype='http://rdfs.org/sioc/ns#UserAccount']") as HTMLElement;
      let contentElement = element.querySelector("[itemprop='http://rdfs.org/sioc/ns#content']") as HTMLElement;

      // 生成一个容器,作为react的渲染容器
      const container = document.createElement('div');
      // 根据UserProfileElement创建user
      let user = createUser(userProfileElement)
      // 判断是否被屏蔽
      let isBlocked = await existBlockUser(user.id);
      // 渲染按钮到指定容器
      ReactDOM.render(
        <React.StrictMode>
          <BlockMaskComponent user={user} isBlocked={isBlocked} />
        </React.StrictMode>,
        container)
      // 将这个容器注入到父容器内
      contentElement.insertBefore(container, contentElement.firstChild);
    });
  }
  else {
    console.log("找不到block mask 注入点");
  }
}